package cryptx

import (
	"crypto/md5"
	"crypto/rand"
	"encoding/base64"
	"encoding/hex"
	"fmt"

	"golang.org/x/crypto/scrypt"
	// "golang.org/x/crypto/bcrypt"
)

func Md5(s string) string { //
	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}

func PasswordEncrypt(salt string, password string) string { // #24.02.24# deprecated
	dk, _ := scrypt.Key([]byte(password), []byte(salt), 32768, 8, 1, 32)

	return fmt.Sprintf("%x", string(dk))
}

func EncryptPasswordWithSalt(password string, salt string) string { // #24.07.31#
	dk, _ := scrypt.Key([]byte(password), []byte(salt), 32768, 8, 1, 32)

	return fmt.Sprintf("%x", string(dk))
}

// bcrypt.CompareHashAndPassword(user.Password, []byte(password)

// GenerateRandomBytes returns n random bytes securely generated using the system's default CSPRNG.
//
// An error will be returned if reading from the secure random number generator fails, at which point
// the returned result should be discarded and not used any further.
func GenerateRandomBytes(n int) ([]byte, error) { // #24.02.24#
	b := make([]byte, n)

	_, err := rand.Read(b)
	if err != nil {
		return nil, err
	}

	// fmt.Sprintf("%06d", rand.Int31n(10000))

	return b, nil
}

// GenerateRandomBase64String returns a string with n random bytes securely generated using the system's
// default CSPRNG in base64 encoding. The resulting string might not be of length n as the encoding for
// the raw bytes generated may vary.
//
// An error will be returned if reading from the secure random number generator fails, at which point
// the returned result should be discarded and not used any further.
func GenerateRandomBase64String(n int) (string, error) { //
	b, err := GenerateRandomBytes(n)
	if err != nil {
		return "", err
	}

	return base64.StdEncoding.EncodeToString(b), nil
}

// GenerateRandomHexString returns a string with n random bytes securely generated using the system's
// default CSPRNG in hexadecimal encoding. The resulting string might not be of length n as the encoding
// for the raw bytes generated may vary.
//
// An error will be returned if reading from the secure random number generator fails, at which point
// the returned result should be discarded and not used any further.
func GenerateRandomHexString(n int) (string, error) { // #24.02.24#
	b, err := GenerateRandomBytes(n)
	if err != nil {
		return "", err
	}

	return hex.EncodeToString(b), nil
}
